Sdl.init [`EVERYTHING]

let get_dims img =
  ((Sdlvideo.surface_info img).Sdlvideo.w, (Sdlvideo.surface_info img).Sdlvideo.h)

(* Draw stokes between different colors *)
let draw_strokes img color =
  let (width, height) = get_dims img in
    for y = 0 to (height) - 1 do
      for x = 0 to (width) - 1 do
	let pixel_color = Sdlvideo.get_pixel_color img ~x:x ~y:y in
	let color1 = Sdlvideo.get_pixel_color img ~x:(x+1) ~y:y in
	let color2 = Sdlvideo.get_pixel_color img ~x:x ~y:(y+1) in
	  if (pixel_color <> color1 || pixel_color <> color2) then
	    Sdlvideo.put_pixel_color img x y color
      done
    done

(* Draw the horizontal grids *)
let draw_grid_horizontal img pas color = 
  let (width,height) = get_dims img in 
  let row_count = height / pas in
   for y = 0 to row_count do
    for x = 0 to width - 1 do
     Sdlvideo.put_pixel_color img x (y*pas) color;
    done
   done

(* Draw the vertical grids *)
let draw_grid_vertical img pas color =
  let (width,height) = get_dims img in 
  let row_count =  width / pas in
   for x = 0 to row_count do
    for y = 0 to height - 1 do
     Sdlvideo.put_pixel_color img (x*pas) y color;
    done

(* Draw the vertical grids *)
let draw_diagonal img pas =
  let (width, height) = get_dims img in
    for x = 0 to width - 1 do
      for y = 0 to height - 1 do
	let color = Sdlvideo.get_pixel_color img x y in
          if x mod pas = y mod pas then
	    if color = strokes_color then
	      Sdlvideo.put_pixel_color img x y inter_color
	    else
              Sdlvideo.put_pixel_color img x y grid_color
      done
    done

(* Display all the grids *)
let draw_grid img pas color =
    draw_grid_horizontal img pas color;
    draw_grid_vertical img pas color

let save img output =
  Sdlvideo.save_BMP img output 

let full_treatment image output pas color_strokes color_grid =
  let img = Sdlloader.load_image image in
    draw_strokes img color_strokes;
    draw_grid img pas color_grid;
    save img output

let is_in_bounds x y width height =
  x >= 0 && y >= 0 && y < height && x < width 

let median_filter img output = 
  let (x,y) = get_dims img in
    for i = 0 to x-1 do
      for j = 0 to y-1 do
	let aver = ref 0 in
 	let aveg = ref 0 in
	let aveb = ref 0 in
 	let count = ref 0 in
	  for a = -1 to 1 do
 	    for b = -1 to 1 do
	      if is_in_bounds (i+a) (j+b) x y then
		let (r,g,b) = Sdlvideo.get_pixel_color img (i+a) (j+b) in
		  begin
	 	    count := !count + 1;
		    aver := !aver + r;
	 	    aveb := !aveb + b;
		    aveg := !aveg + g;
		  end;
	    done;
	  done; 
 	  Sdlvideo.put_pixel_color img i j (!aver / (!count), !aveg / (!count), !aveb / (!count))        
      done;
    done;
    save img output

	  
	  
